/*
 * @Author: dell di
 * @Date: 2022-05-22 13:03:35
 * @LastEditTime: 2022-05-22 21:57:10
 * @LastEditors: di
 * @Description:
 * @FilePath: \base-vue3.2-ts\src\utils\file.ts
 */
export const dataURLtoFile = function (
  dataurl: ReturnType<HTMLCanvasElement['toDataURL']>,
  filename = `${Date.now()}`
): File {
  const arr = dataurl.split(','),
    mime = ((arr[0] || '').match(/:(.*?);/) as string[])[1],
    bstr = atob(arr[1]),
    u8arr = new Uint8Array(n)
  let n = bstr.length
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {
    type: mime
  })
}

// file转base64
export function fileToBase64(file: File, callback: (e: string | ArrayBuffer) => void) {
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = function (e) {
    e.target && e.target.result && callback(e.target.result)
  }
}
